using System;
using AI;

namespace AI.FSM
{
    public class FSM<T> : IBehaviour<T,FSMRunState>
    {
        public FSM(FSMState<T>[] states)
        {
            this.states = states;
        }

        public FSMRunState Init(T agent)
        {
            return FSMRunState.EnterState;
        }

        public void Run(T agent, FSMRunState state)
        {
            var currentState = this.states[state.CurrentState];
            if(state.PreviousState != state.CurrentState)
            {
                currentState.OnEnter(agent);
                state.PreviousState = state.CurrentState;
            }
            
            currentState.OnTick(agent);

            for(int i = 0; i < currentState.Transitions.Length; i++)
            {
                var transition = currentState.Transitions[i];
                if(transition.Condition(agent))
                {
                    state.CurrentState = transition.TargetState;
                    break;
                }
            }

            if(state.PreviousState != state.CurrentState)
            {
                currentState.OnExit(agent);
            }
        }

        FSMState<T>[] states;
    }
}
